package com.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Iterator;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;

import com.constants.Constants;
import com.model.HttpResponseObject;

public class HttpUtils {

	// http请求的默认编码
	private static String BASE_HTTP_ENCODE = Constants.BASE_HTTP_ENCODE;
	// 请求的最大尝试次数
	private static int MAX_RETRY = Constants.MAX_RETRY;

	/**
	 * 根据url返回该图片的bitmap封装的对象
	 * 
	 * @param url
	 * @return
	 */
	public static Bitmap returnBitMap(String url) {
		URL myFileUrl = null;
		Bitmap bitmap = null;
		try {
			myFileUrl = new URL(url);
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
		try {
			HttpURLConnection conn = (HttpURLConnection) myFileUrl
					.openConnection();
			conn.setDoInput(true);
			conn.connect();
			Log.i("获取网络图片", url);
			InputStream is = conn.getInputStream();
			bitmap = BitmapFactory.decodeStream(is);
			is.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return bitmap;
	}

	/**
	 * 验证文本是否与正则匹配
	 * 
	 * @param reg
	 * @param testStr
	 * @return
	 */
	public static boolean isMatch(String reg, String testStr) {
		Pattern pattern = Pattern.compile(reg);
		Matcher matcher = pattern.matcher(testStr);
		return matcher.matches();
	}

	/**
	 * 判断是否是空字符串
	 * 
	 * @param str
	 * @return
	 */
	public static boolean isEmptyString(String str) {
		return str == null || str.trim().length() == 0;
	}

	/**
	 * 通过http请求获取内容
	 * 
	 * @param url
	 * @param params
	 * @return
	 */
	public static HttpResponseObject getInfoFromUrl(String url,
			Map<String, Object> params) {
		if (!url.endsWith("?")) {
			url += "?";
		}
		Iterator<String> it = params.keySet().iterator();
		boolean isFirst = true;
		while (it.hasNext()) {
			String key = it.next();
			Object val = params.get(key);
			if (isFirst) {
				isFirst = false;
			} else {
				url += "&";
			}
			url += key + "=" + val.toString();
		}
		return getInfoFromUrl(url, BASE_HTTP_ENCODE);
	}

	/**
	 * 通过http请求获取内容
	 * 
	 * @param url
	 * @return
	 */
	public static HttpResponseObject getInfoFromUrl(String url) {
		return getInfoFromUrl(url, BASE_HTTP_ENCODE);
	}

	/**
	 * 通过http请求获取内容
	 * 
	 * @param url
	 * @param encode
	 * @return
	 */
	public static HttpResponseObject getInfoFromUrl(String url, String encode) {
		if (encode == null || encode.trim().length() == 0) {
			encode = BASE_HTTP_ENCODE;
		}
		StringBuilder sb = new StringBuilder();
		int retry = MAX_RETRY;
		int state = 0;
		HttpURLConnection httpConnection = null;
		while (retry > 0) {
			try {
				httpConnection = (HttpURLConnection) new URL(url)
						.openConnection();
				httpConnection.setRequestMethod("GET");
				httpConnection.connect();
				int num = MAX_RETRY - retry + 1;
				Log.i("getInfoFromUrl", "第" + num + "次获取 \"" + url + "\" 信息");
				int code = httpConnection.getResponseCode();
				if (code == HttpURLConnection.HTTP_OK) {
					BufferedReader in = new BufferedReader(
							new InputStreamReader(
									httpConnection.getInputStream(), encode));
					while (in.ready()) {
						sb.append(in.readLine());
					}
					break;
				}
			} catch (MalformedURLException e) {
				Log.e("getInfoFromUrl", url + "不合法\n" + e.getMessage());
				state = 1;
				break;
			} catch (UnsupportedEncodingException e) {
				Log.e("getInfoFromUrl", url + "[" + encode + "]"
						+ "不支持的encoding\n" + e.getMessage());
				state = 1;
				break;
			} catch (Exception e) {
				Log.e("getInfoFromUrl", e.getMessage());
				state = 2;
				break;
			} finally {
				retry--;
			}
		}
		String result = sb.toString();
		return new HttpResponseObject(state, result.trim().length() == 0 ? "{}"
				: result);
	}
}
